package com.ccut.xunfeiSpringboot.utils;/*
 * ClassName: WordParserUtils
 * Package: com.ccut.xunfeiSpringboot.utils
 * Description:
 * @Author 刘千湫
 * @Create 2025/6/2 22:11
 * @Version 1.0
 */

import com.ccut.xunfeiSpringboot.common.AjaxResult;
import com.ccut.xunfeiSpringboot.dto.SchoolResumeDTO;
import com.ccut.xunfeiSpringboot.dto.StudentResumeDTO;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class WordParserUtils {
    public AjaxResult parseStudentDoc(InputStream inputStream) throws Exception {
        XWPFDocument document = new XWPFDocument(inputStream);

        List<String> targetFields = Arrays.asList(
                "姓名", "性别", "邮箱", "电话", "教育背景", "学历", "技能特长",
                "实习经历", "校园经历", "科技竞赛", "自我评价"
        );

        Map<String, String> fieldMap = new HashMap<>();
        for (String field : targetFields) {
            fieldMap.put(field.trim().toLowerCase(), field);
        }

        Map<String, StringBuilder> resultBuilders = new LinkedHashMap<>();
        String currentField = null;

        for (XWPFParagraph paragraph : document.getParagraphs()) {
            String rawText = paragraph.getText();
            if (rawText == null || rawText.trim().isEmpty()) continue;
            String text = rawText.replaceAll("[\\u200B\\u200C\\u200D\\uFEFF\\u2060\\s]+", " ").trim();

            boolean isField = false;
            for (String key : fieldMap.keySet()) {
                if (text.contains(key)) {
                    currentField = fieldMap.get(key);
                    resultBuilders.putIfAbsent(currentField, new StringBuilder());

                    int colonIndex = text.indexOf("：");
                    if (colonIndex < 0) colonIndex = text.indexOf(":");
                    if (colonIndex < 0) colonIndex = text.indexOf("——");
                    if (colonIndex < 0) colonIndex = text.indexOf("、");

                    if (colonIndex > -1 && colonIndex < text.length() - 1) {
                        String valuePart = text.substring(colonIndex + 1).trim();
                        if (!valuePart.isEmpty()) {
                            resultBuilders.get(currentField).append(valuePart).append("\n");
                        }
                    } else {
                        currentField = fieldMap.get(key);
                        resultBuilders.putIfAbsent(currentField, new StringBuilder());
                    }
                    isField = true;
                    break;
                }
            }
            if (!isField && currentField != null) {
                resultBuilders.get(currentField).append(text).append("\n");
            }
        }

        Map<String, String> result = new HashMap<>();
        for (Map.Entry<String, StringBuilder> entry : resultBuilders.entrySet()) {
            result.put(entry.getKey(), entry.getValue().toString().trim());
        }

        StudentResumeDTO dto = new StudentResumeDTO();
        dto.setName(result.get("姓名"));
        dto.setSex(result.get("性别"));
        dto.setEmail(result.get("邮箱"));
        dto.setTelephone(result.get("电话"));
        dto.setEducationBackground(result.get("教育背景"));
        String educationStr = result.get("学历");
        if (educationStr != null && !educationStr.isEmpty()) {
            Integer recordInt;

            switch (educationStr.trim()) {
                case "专科":
                case "大专":
                    recordInt = 0;
                    break;
                case "本科":
                case "学士":
                    recordInt = 1;
                    break;
                case "硕士":
                case "研究生":
                    recordInt = 2;
                    break;
                case "博士":
                case "博士后":
                    recordInt = 3;
                    break;
                default:
                    recordInt = null; // 或根据业务需求设为 -1 或抛异常
                    break;
            }

            dto.setRecord(recordInt);
        }
        dto.setSkills(result.get("技能特长"));
        dto.setInternshipExperience(result.get("实习经历"));
        dto.setCampusExperience(result.get("校园经历"));
        dto.setTechCompetition(result.get("科技竞赛"));
        dto.setSelfEvaluation(result.get("自我评价"));
        return AjaxResult.success(dto);
    }


    public AjaxResult parseSchoolDoc(InputStream inputStream) throws Exception {
        Map<String, String> result = new HashMap<>();
        try (XWPFDocument doc = new XWPFDocument(inputStream)) {
            parseSchoolParagraphs(doc.getParagraphs(), result);
            parseTables(doc.getTables(), result);
        }

        SchoolResumeDTO dto = new SchoolResumeDTO();
        dto.setSchoolName(result.get("学校"));
        dto.setAddress(result.get("地址"));
        dto.setContactNumber(result.get("联系方式"));
        dto.setPrincipal(result.get("校长"));
        dto.setEstablishedYear(result.get("成立时间"));
        dto.setDescription(result.get("学校简介"));

        return AjaxResult.success(dto);
    }

    private void parseParagraphs(List<XWPFParagraph> paragraphs, Map<String, String> result) {
    // 定义标准字段列表（按你指定的顺序）
    List<String> fields = Arrays.asList(
            "姓名", "性别", "邮箱", "电话", "教育背景", "学历", "技能特长",
            "实习经历", "校园经历", "科技竞赛", "自我评价"
    );

    // 构建一个 map 用于模糊匹配（去除空格、大小写不敏感）
    Map<String, String> fieldMap = new HashMap<>();
    for (String field : fields) {
        fieldMap.put(field.trim().toLowerCase(), field);
    }

    // 当前正在读取的字段
    String currentField = null;
    StringBuilder currentValue = new StringBuilder();

    for (XWPFParagraph paragraph : paragraphs) {
        String text = paragraph.getText().trim();
        if (text.isEmpty()) continue;

        // 尝试识别字段名
        boolean isField = false;
        for (String field : fields) {
            if (text.startsWith(field + "：") || text.startsWith(field + ":")) {
                // 匹配到字段名+冒号
                if (currentField != null) {
                    result.put(currentField, currentValue.toString().trim());
                }
                currentField = field;
                currentValue = new StringBuilder(text.substring(field.length() + 1).trim());
                isField = true;
                break;
            } else if (field.equalsIgnoreCase(text)) {
                // 独占一行的字段名（比如“学历”单独成行）
                if (currentField != null) {
                    result.put(currentField, currentValue.toString().trim());
                }
                currentField = field;
                currentValue = new StringBuilder();
                isField = true;
                break;
            }
        }

        if (!isField && currentField != null) {
            // 继续拼接到当前字段
            currentValue.append("\n").append(text);
        }
    }

    // 处理最后一个字段
    if (currentField != null) {
        result.put(currentField, currentValue.toString().trim());
    }
}
    private void parseSchoolParagraphs(List<XWPFParagraph> paragraphs, Map<String, String> result) {
        Pattern pattern = Pattern.compile(
                "(学校|用户名|密码|地址|邮箱|联系方式|校长|成立时间|学校简介)[：:](\\s*)(.+)");

        for (XWPFParagraph para : paragraphs) {
            String text = para.getText().trim();
            Matcher matcher = pattern.matcher(text);
            if (matcher.find()) {
                String key = matcher.group(1);
                String value = matcher.group(3).trim();
                result.put(key, value);
            }
        }
    }
    private void parseTables(List<XWPFTable> tables, Map<String, String> result) {
        for (XWPFTable table : tables) {
            for (int rowIdx = 0; rowIdx < table.getNumberOfRows(); rowIdx++) {
                XWPFTableRow row = table.getRow(rowIdx);
                for (int colIdx = 0; colIdx < row.getTableCells().size(); colIdx++) {
                    XWPFTableCell cell = row.getCell(colIdx);
                    String cellText = cell.getText().trim();
                    if (cellText.contains("姓名") && colIdx + 1 < row.getTableCells().size()) {
                        result.put("姓名", row.getCell(colIdx + 1).getText());
                    }
                }
            }
        }
    }
}